package com.example.demo.controller;

import com.example.demo.mapper.UserMapper;
import com.example.demo.pojo.Announcement;
import com.example.demo.pojo.PageBean;
import com.example.demo.pojo.Result;
import com.example.demo.pojo.User;
import com.example.demo.service.AnnouncementService;
import com.example.demo.service.UserService;
import com.example.demo.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/announcement")
public class AnnouncementController {

    @Autowired
    private AnnouncementService announcementService;
    @Autowired
    private UserService userService;

    public boolean Authentication() {
        Map<String, Object> map = ThreadLocalUtil.get();
        String phonenumber = (String) map.get("phonenumber");
        User u = userService.findByphoneNumber(phonenumber);
        if (u.getUsertype() != 1) {
            return false;
        }
        return true;
    }

    @PostMapping("/add")
    public Result add(@RequestBody @Validated Announcement announcement) {
        if(!Authentication()){
            return Result.error("权限不足");
        }
        announcementService.add(announcement);
        return Result.success();
    }

//    @GetMapping("/list")
//    public Result<List<Announcement>> list() {
//        return Result.success(announcementService.findAll());
//    }

    @GetMapping("/list")
    public Result<PageBean<Announcement>> list(
            int pageNum,
            int pageSize,
            @RequestParam(required = false) Integer categoryId
    ){
        PageBean<Announcement> pb = announcementService.list(pageNum, pageSize, categoryId);
        return Result.success(pb);
    }




}
